<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card>
        <el-tabs>
          <!-- 放置页签 -->
          <el-tab-pane label="角色管理">
            <!-- 新增角色按钮 -->
            <el-row style="height: 60px">
              <el-button
                icon="el-icon-plus"
                size="small"
                type="primary"
                @click="showDialog = true"
              >新增角色</el-button>
            </el-row>
            <!-- 表格 -->
            <el-table border="" :data="list">
              <el-table-column label="序号" width="120" type="index">
                <template v-slot="slot">
                  {{ (page.page - 1) * page.pagesize + slot.$index + 1 }}
                </template>
              </el-table-column>
              <!-- <el-table-column label="序号" width="120" type="index" /> -->
              <el-table-column label="角色名称" width="240" prop="name" />
              <el-table-column label="描述" prop="description" />
              <el-table-column label="操作">
                <template v-slot:default="{ row }">
                  <el-button
                    size="small"
                    type="success"
                    @click="assignPerm(row.id)"
                  >分配权限</el-button>
                  <el-button
                    size="small"
                    type="primary"
                    @click="editRole(row.id)"
                  >编辑</el-button>
                  <el-button
                    size="small"
                    type="danger"
                    @click="deleteRole(row.id)"
                  >删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <!-- 分页组件 -->
            <el-row
              type="flex"
              justify="center"
              align="middle"
              style="height: 60px"
            >
              <!-- 分页组件 -->
              <el-pagination
                layout="total,sizes,prev,pager,next"
                :total="total"
                :page-size="page.pagesize"
                :page-sizes="pagesizes"
                @current-change="currentChange"
                @size-change="sizeChange"
              />
            </el-row>
          </el-tab-pane>
          <el-tab-pane label="公司信息">
            <el-alert
              title="对公司名称、公司地址、营业执照、公司地区的更新，将使得公司资料被重新审核，请谨慎修改"
              type="info"
              show-icon
              :closable="false"
            />
            <el-form
              v-model="formData"
              label-width="120px"
              style="margin-top: 50px"
            >
              <el-form-item label="公司名称">
                <el-input
                  v-model="formData.name"
                  disabled
                  style="width: 400px"
                />
              </el-form-item>
              <el-form-item label="公司地址">
                <el-input
                  v-model="formData.companyAddress"
                  disabled
                  style="width: 400px"
                />
              </el-form-item>
              <el-form-item label="邮箱">
                <el-input
                  v-model="formData.mailbox"
                  disabled
                  style="width: 400px"
                />
              </el-form-item>
              <el-form-item label="备注">
                <el-input
                  v-model="formData.remarks"
                  type="textarea"
                  :rows="3"
                  disabled
                  style="width: 400px"
                />
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>
      </el-card>
      <!-- 编辑角色弹框 -->
      <el-dialog :title="title" :visible="showDialog" @close="btnCancel">
        <el-form
          ref="roleForm"
          :model="roleForm"
          :rules="rules"
          label-width="120px"
        >
          <el-form-item label="角色名称" prop="name">
            <el-input v-model="roleForm.name" />
          </el-form-item>
          <el-form-item label="角色描述" prop="description">
            <el-input v-model="roleForm.description" />
          </el-form-item>
        </el-form>
        <!-- 底部 -->
        <el-row slot="footer" type="flex" justify="center">
          <el-col :span="6">
            <el-button size="small" @click="btnCancel">取消</el-button>
            <el-button
              size="small"
              type="primary"
              @click="btnOK"
            >确定</el-button>
          </el-col>
        </el-row>
      </el-dialog>
      <el-dialog
        title="分配权限"
        :visible="showPermDialog"
        @close="btnPermCancel"
      >
        <!-- 权限是一颗树 -->
        <!-- 将数据绑定到组件上 -->
        <!-- check-strictly 如果为true 那表示父子勾选时  不互相关联 如果为false就互相关联 -->
        <!-- id作为唯一标识 -->
        <el-tree
          ref="permTree"
          :data="permData"
          :props="{ label: 'name' }"
          :show-checkbox="true"
          :check-strictly="true"
          :default-expand-all="true"
          :default-checked-keys="selectCheck"
          node-key="id"
        />
        <!-- 确定 取消 -->
        <el-row slot="footer" type="flex" justify="center">
          <el-col :span="6">
            <el-button
              type="primary"
              size="small"
              @click="btnPermOK"
            >确定</el-button>
            <el-button size="small" @click="btnPermCancel">取消</el-button>
          </el-col>
        </el-row>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import {
  getCompanyInfo,
  getRoleList,
  deleteRole,
  getRoleDetail,
  updateRole,
  addRole,
  assignPerm
} from '@/api/setting'
import { getPermissionList } from '@/api/permission'
export default {
  data() {
    return {
      permData: [], // 权限列表 接收树形数据
      formData: {
        name: '',
        companyAddress: '',
        mailbox: '',
        remarks: ''
      },
      list: [],
      total: 0,
      page: {
        page: 1,
        pagesize: 2
      },
      pagesizes: [2, 5, 10, 20],
      roleForm: {
        name: '',
        description: ''
      },
      rules: {
        name: [
          { required: true, message: '角色名称不能为空！', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '角色描述不能为空！', trigger: 'blur' }
        ]
      },
      showDialog: false,
      showPermDialog: false,
      selectCheck: [], // 已经选中的节点
      roleId: ''
    }
  },
  computed: {
    title() {
      return this.roleForm.id ? '编辑角色' : '新增角色'
    }
  },
  created() {
    this.getCompanyInfo()
    this.getRoleList()
    // 获取权限列表
    this.getPermissionList()
  },
  methods: {
    // 分配权限
    async assignPerm(id) {
      // console.log(id)
      // 获取当前角色拥有的权限点
      this.roleId = id
      const { permIds } = await getRoleDetail(id)
      // console.log(permIds)
      this.selectCheck = permIds
      this.showPermDialog = true
    },
    async btnPermOK() {
      // 利用树形组件提供的内置方法getCheckedKeys获取以被选择的节点组成的数组
      const newSelectCheck = this.$refs.permTree.getCheckedKeys()
      // console.log(newSelectCheck)
      // 发起给角色分配权限请求
      await assignPerm({ permIds: newSelectCheck, id: this.roleId })
      this.$message.success('分配权限成功！')
      this.showPermDialog = false
    },
    btnPermCancel() {
      this.selectCheck = []
      this.showPermDialog = false
    },
    // 获取所有权限
    async getPermissionList() {
      const res = await getPermissionList()
      // console.log(res)
      this.permData = this.transListToTreeData(res, '0')
    },
    async editRole(id) {
      // console.log(id)
      this.roleForm = await getRoleDetail(id)
      this.showDialog = true
    },
    btnOK() {
      // console.log(this.roleForm)
      this.$refs.roleForm.validate(async(isOK) => {
        if (isOK) {
          if (this.roleForm.id) {
            // 编辑
            await updateRole(this.roleForm)
          } else {
            // 新增
            await addRole(this.roleForm)
          }
          // 小小优化 等待数据更新完成再提示
          await this.getRoleList()
          this.$message.success('操作成功！')
          this.showDialog = false
        }
      })
    },
    btnCancel() {
      this.roleForm = {
        name: '',
        description: ''
      }
      this.$refs.roleForm.resetFields()
      this.showDialog = false
    },
    async deleteRole(id) {
      this.$confirm('确定删除该角色吗？')
        .then(async() => {
          await deleteRole(id)
          this.$message.success('删除角色成功！')
          this.getRoleList()
        })
        .catch(() => {
          this.$message.error('已取消删除！')
        })
    },
    sizeChange(newSize) {
      // console.log(newSize)
      this.page.pagesize = newSize
      this.getRoleList()
    },
    currentChange(newPage) {
      // console.log(newPage)
      this.page.page = newPage
      this.getRoleList()
    },
    async getCompanyInfo() {
      const companyId = this.$store.getters.companyId
      this.formData = await getCompanyInfo(companyId)
    },
    async getRoleList() {
      const { rows, total } = await getRoleList(this.page)
      this.list = rows
      this.total = total
    },
    transListToTreeData(list, rootId) {
      const arr = []
      list.forEach((item) => {
        if (item.pid === rootId) {
          const children = this.transListToTreeData(list, item.id)
          if (children.length) {
            item.children = children
          }
          arr.push(item)
        }
      })
      return arr
    }
  }
}
</script>

<style>
</style>
